# router.py
from collections.abc import Callable
from typing import Any

from .models import HEMCConfig


class ConfigRouter:
    """配置路由器：自动收集并分发命令"""

    def __init__(self):
        self._registry = {}

    def register(self, name: str | None = None):
        """装饰器：注册配置处理器"""

        def decorator(func: Callable):
            cmd_name = name or func.__name__
            self._registry[cmd_name] = func
            return func

        return decorator

    def dispatch(self, config: HEMCConfig) -> Any:
        """执行函数列表中的第一个函数"""
        if not config.call:
            raise ValueError('Need at least one function to call')
        cmd = config.call[0]

        func = self._registry.get(cmd.func)
        if not func:
            available = ", ".join(self._registry)
            raise ValueError(f"未知的调用目标: '{cmd}'，可用: {available}")

        return func(config)

    def dispatch_multi(self, config: HEMCConfig) -> Any:
        """依次执行函数列表中的函数"""
        cmds = config.call
        rets = []
        for cmd in cmds:
            func = self._registry.get(cmd.func)
            if not func:
                available = ", ".join(self._registry)
                raise ValueError(f"未知的调用目标: '{cmd}'，可用: {available}")

            ret = func(config)
            rets.append(ret)
        return rets

    @property
    def commands(self):
        return list(self._registry)


# 模块级单例（Python 的模块本身就是单例）
# 其他文件通过 `from router import router` 获取同一实例
router = ConfigRouter()
